<?php
/**
 * 	Bushido
 *
 * @category   Bushido
 * @package    Bushido_Table
 * @copyright  Copyright (c) 2008-2009 Nathan Keyes
 * @author Nathan Keyes
 * @version    $Id: Table.php 71 2009-11-15 19:27:36Z nkeyes $
 */

/**
 * 
 * @author Nathan Keyes
 *
 */
class Bushido_Db_Table
{
	
	protected static $_adapter = NULL;
	
	/**
	 * 
	 * @return void
	 */
	public function __construct(){}
	
	
	/**
	 * 
	 * @return void
	 */
	public function __clone(){}
	
	/**
	 * 
	 * @return Bushido_Db_Table_Abstract
	 * @param $tableName Object
	 * @param $config array[optional]
	 */
	public static function getTable($tableName, $config = array())
	{
		return new $tableName($config);
	}
	
	
	/**
	 * 
	 * @return Zend_Db_Adapter_Abstract
	 */
	public static function getAdapter()
	{
		if(!self::$_adapter)
		{
			self::$_adapter = Bushido_App::getAdapter();
		}
		else
		{
			//Zend_Debug::dump(self::$_adapter, 'existing adapter');
		}
		
		return self::$_adapter;
	}
	/**
	 * 
	 * @param Zend_Db_Table_Row_Abstract $row
	 * @param mixed $context
	 * @return string
	 */
	public static function getDisplayValue(Zend_Db_Table_Row_Abstract $row, $context = null)
	{
		return $row->getTable()->getDisplayValue($row, $context);
	}
	
	/**
	 * 
	 * @param unknown_type $table
	 * @param unknown_type $pk
	 * @return Bushido_Db_Table_Row
	 */
	public static function generateRow($table, $pk)
	{
		$row = null;
		
		
		if(!$table instanceof Bushido_Db_Table_Abstract)
		{
			$table = Bushido_Db_Table::getTable((string)$table);
		}
		$adapter = $table->getAdapter();
		$select = $table->select();
		foreach($pk as $field=> $value)
		{
			$select = $select->where("$field = ?", $value);
		}
		$data = $adapter->fetchRow("$select");
		
		//Zend_Debug::dump($data);exit;
		if(!empty($data))
		{
			$row = new Bushido_Db_Table_Row
			(
				array
				(
					'table'    => $table,
					'data'     => $data,
					'stored'   => true,
					'readOnly' => false
				)
			);
		}
		else
		{
			throw new Bushido_Db_Table_Exception_RowNotFound;
		}
		
		return $row;
	}
	
/**
	 * 
	 * @param $rowset
	 * @return Zend_Dojo_Data
	 */
	public static function rowsetGridJson(Zend_Db_Table_Rowset_Abstract $rowset, $sortColumn, $sortDirection, $limit, $offset, $totalRecords)
	{
		$rowsetArray = array();
		$table = $rowset->getTable();
		$primary = $table->info('primary');
		if($rowset->count())
		{
			//var_dump($rowset->count());
			foreach($rowset as $row)
			{
				$rowArray = $row->toArray();
				
				if($table->getExtraGridFields())
				{
					foreach($table->getExtraGridFields() as $extraField)
					{
						if($extraField['isParent'])
						{
							$findFunction = 'findParent' . $extraField['class'];
						}
						else
						{
							$findFunction = 'find' . $extraField['class'];
						}
						if(isset($extraField['middleManClass']))
						{
							 $findFunction .= 'Via' . $extraField['middleManClass'];
						}
						$subRows = $row->$findFunction();
						if($subRows)
						{
							$subRowsValue = '';
							foreach($subRows as $subRow)
							{
								$subRowsValue .= Bushido_Db_Table::getDisplayValue($subRow) . "\n";
							}
							$rowArray[$extraField['field']] = $subRowsValue;
						}
					}
				}
				$references = $table->getReferenceMap();
				foreach($rowArray as $field => $value)
				{
					$metaData = $table->info(Zend_Db_Table::METADATA);
					if(stripos($metaData[$field]['DATA_TYPE'], 'blob') !== false || stripos($metaData[$field]['DATA_TYPE'], 'bin') !== false)
					{
						$rowArray[$field] = null;
						continue;
					}
					foreach($references as $reference => $referenceData)
					{	
						if($field === $referenceData[Zend_Db_Table_Abstract::COLUMNS] && !empty($value))
						{
							
							$refTable = Bushido_Db_Table::getTable($referenceData[Zend_Db_Table_Abstract::REF_TABLE_CLASS]);
							//Zend_Debug::dump($value);
							$refRecord = $refTable->search(array($referenceData[Zend_Db_Table_Abstract::REF_COLUMNS] => $value))->current();
							
							
							try
							{
								if($refRecord)
								{
									$pk = $refRecord->getPK();
									//Zend_Debug::dump($pk);
								
									$rowArray[$field] = Bushido_Db_Table::generateRow($referenceData[Zend_Db_Table_Abstract::REF_TABLE_CLASS], $pk)->getDisplayValue();
								}
								else
								{
									$rowArray[$field] = $value;
								}
							}
							catch(Exception $e)
							{
								throw $e;
							}
						}
					}
				}
				$rowsetArray[] = $rowArray;
			}
		}
		$data = array();
		
		if($totalRecords)
		{
			$data['totalRecords'] = $totalRecords;
		}
		$data['startIndex'] = intval($offset);
		
		$data['sort'] = $sortColumn;
		
		if($sortDirection)
		{
			$data['dir'] = $sortDirection;
		}
		if($limit)
		{
			$data['pageSize'] = $limit;
		}
		$data['records'] = $rowsetArray;
		$data = Zend_Json_Encoder::encode($data);
		
		return $data;
	}
}
